import { formatToTreeArr } from '@/utils/format';
import { Modal, Tree } from 'antd';
import type { TreeProps } from 'antd/es/tree';
import { useEffect, useMemo, useState } from 'react';
import menuApi from './menu-request';

export interface Props {
  visible: boolean;
  data?: Partial<RoleManagementApi.InfoResponse>;
  onSuccess?: () => void;
  onCancel?: () => void;
}

function RoleModal(props: Props) {
  const { visible, data } = props;

  const [checkedMenu, setCheckedMenu] = useState<MenuManagementApi.GetRelationResponse[]>([]);
  const [treeMenu, setTreeMenu] = useState<
    Requestor.TargetTree<MenuManagementApi.GetRelationResponse>[]
  >([]);
  const checkedKeys = useMemo(() => checkedMenu.map((item) => item.id), [checkedMenu]);

  const getRelation = async (params: MenuManagementApi.GetRelationParams) => {
    const data = await menuApi.getRelation(params);
    const checkedMenu = data.filter((item) => item.isChoose);
    setCheckedMenu(checkedMenu);
    setTreeMenu(formatToTreeArr(data));
  };
  const postRelation = async (params: MenuManagementApi.PostRelationParams) => {
    const data = await menuApi.postRelation(params);
    if (data.success) props.onSuccess?.();
  };

  useEffect(() => {
    if (visible && data?.id) {
      getRelation({ RoleId: data.id });
    }
  }, [visible, data]);

  const onCheck: TreeProps['onCheck'] = (_, info) => {
    const checkedMenu = info.checkedNodes as unknown as MenuManagementApi.GetRelationResponse[];
    setCheckedMenu(checkedMenu);
  };
  const onConfirm = () => {
    const params: MenuManagementApi.PostRelationParams = {
      roleId: data?.id || '',
      createUserRoleRelationshipDataSysMenuList: checkedMenu.map((item) => ({
        sysMenuId: item.id,
        sysTitle: item.title,
      })),
    };
    postRelation(params);
  };
  const onCancel = () => {
    props.onCancel?.();
  };

  return (
    <Modal title="菜单权限" open={visible} onOk={onConfirm} onCancel={onCancel}>
      <Tree checkable checkedKeys={checkedKeys} treeData={treeMenu} onCheck={onCheck} />
    </Modal>
  );
}

export default RoleModal;
